package com.xiaomi.servlet;

import cn.dsna.util.images.ValidateCode;
import com.xiaomi.entity.User;
import com.xiaomi.service.UserService;
import com.xiaomi.service.impl.UserServiceImpl;
import com.xiaomi.utils.MD5Utils;
import com.xiaomi.utils.RandomUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends BaseServlet {

    private final UserService userService = new UserServiceImpl();

    /**
     * 检查注册时的用户名是否重复
     */
    protected String checkUser(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        if (username != null && !"".equals(username)) {
            User user = userService.checkUser(username);
            if (user != null) {
                //返回1表示用户名已存在
                return "1";
            }
        }
        //其他情况返回0
        return "0";
    }

    /**
     * 用户注册
     */
    protected String register(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Map<String, String[]> map = req.getParameterMap();
            User user = new User();
            BeanUtils.populate(user, map);
            user.setState(0);//0表示邮箱未激活
            user.setRole(0);//0表示普通会员
            user.setCode(RandomUtils.createActive());//设置激活码
            //用户密码MD5加密
            user.setPassword(MD5Utils.md5(user.getPassword()));
            int count = userService.register(user);
            if (count > 0) {
                //插入成功 转发到注册成功页面
                return "forward:/registerSuccess.jsp";
            }
            System.out.println("2222");
            req.setAttribute("msg", "注册失败");
            //失败到消息提示页面
            return "forward:/message.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            //失败到消息提示页面
            return "forward:/message.jsp";
        }
    }

    /**
     * 用户登录
     */
    protected String login(HttpServletRequest req, HttpServletResponse resp) {
        String code = (String) req.getSession().getAttribute("code");
        String inputCode = req.getParameter("code");
        String auto = req.getParameter("auto");
        //验证验证码
        if (code != null && !code.equalsIgnoreCase(inputCode)) {
            req.setAttribute("msg", "登陆失败,验证码输入错误!");
            return "forward:/login.jsp";
        }
        //验证用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username != null && !"".equals(username) && password != null && !"".equals(password)) {
            //在查询时传入的密码也需要加密
            password = MD5Utils.md5(password);
            User user = userService.login(username, password);
            if (user != null) {
                //查询成功,将用户对象存入会话中,返回首页
                req.getSession().setAttribute("loginUser", user);
                if ("on".equals(auto)) {
                    //设置cookie值为用户名和密码的组合，设置cookie存活时间为2周
                    Cookie cookie = new Cookie("on", username + ":" + password);
                    cookie.setMaxAge(14 * 24 * 60 * 60);
                    resp.addCookie(cookie);
                }
                return "redirect:/index.jsp";
            }
        }
        //未查询到用户.返回登录页面
        req.setAttribute("msg", "登录失败,用户名或密码错误!");
        return "forward:/login.jsp";
    }

    /**
     * 用户注销
     */
    protected String logout(HttpServletRequest req, HttpServletResponse resp) {
        //移除用户session
        req.getSession().removeAttribute("loginUser");
        //注销后 销毁cookie
        Cookie cookie = new Cookie("on", "");
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
        return "redirect:/index.jsp";
    }

    /**
     * 验证码
     */
    protected void code(HttpServletRequest req, HttpServletResponse resp) {
        try {
            //生成验证码图片
            ValidateCode validateCode = new ValidateCode(120, 40, 4, 100);
            validateCode.createCode();
            validateCode.write(resp.getOutputStream());
            //将验证码存入session中
            req.getSession().setAttribute("code", validateCode.getCode());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
